package org.dromara.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.domain.AuditDto;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.erp.domain.*;
import org.dromara.erp.mapper.*;
import org.dromara.erp.service.IErpWarehousingService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 采购入库Service业务层处理
 *
 * @author Mr Lei
 * @date 2024-06-05
 */
@RequiredArgsConstructor
@Service
public class ErpWarehousingServiceImpl implements IErpWarehousingService {

    private final ErpWarehousingMapper baseMapper;
    private final ErpWarehousingInfoMapper infoMapper;
    private final ErpProductsMapper productsMapper;
    private final ErpGoodsInOutInfoMapper goodsInOutInfoMapper;
    private final ErpUnitAttrMapper unitAttrMapper;

    /**
     * 查询采购入库
     */
    @Override
    public ErpWarehousing queryById(Long id){
        //查询主表
        ErpWarehousing warehousing = baseMapper.findById(id);
        //查询子表
        List<ErpWarehousingInfo> infoList = infoMapper.findByMainId(id);
        //设置主表
        warehousing.setContentInfo(infoList);
        return warehousing;
    }

    /**
     * 查询采购入库列表
     */
    @Override
    public TableDataInfo<ErpWarehousing> queryPageList(ErpWarehousing bo, PageQuery pageQuery) {
        Page<ErpWarehousing> result = baseMapper.queryPageList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询采购入库列表
     */
    @Override
    public List<ErpWarehousing> queryList(ErpWarehousing bo) {
        LambdaQueryWrapper<ErpWarehousing> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<ErpWarehousing> buildQueryWrapper(ErpWarehousing bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpWarehousing> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), ErpWarehousing::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getSupplierId() != null, ErpWarehousing::getSupplierId, bo.getSupplierId());
        lqw.eq(bo.getTotalNum() != null, ErpWarehousing::getTotalNum, bo.getTotalNum());
        lqw.eq(bo.getTotalMoney() != null, ErpWarehousing::getTotalMoney, bo.getTotalMoney());
        lqw.eq(bo.getWorkerId() != null, ErpWarehousing::getWorkerId, bo.getWorkerId());
        lqw.eq(bo.getBuyTime() != null, ErpWarehousing::getBuyTime, bo.getBuyTime());
        lqw.eq(StringUtils.isNotBlank(bo.getAuditStatus()), ErpWarehousing::getAuditStatus, bo.getAuditStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ErpWarehousing::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增采购入库
     */
    @Override
    public Boolean insert(ErpWarehousing bo) {
        validEntityBeforeSave(bo);
        boolean flag = baseMapper.insert(bo) > 0;
        if (flag) {
            //获取主表ID
            bo.setId(bo.getId());
            //查到关联的子表列
            List<ErpWarehousingInfo> infoList = bo.getContentInfo();
            //遍历子表
            infoList.forEach(x->{
                x.setOrderId(bo.getId());
                //执行子表保存的方法
                infoMapper.insert(x);
            });
        }
        return flag;
    }

    /**
     * 修改采购入库
     */
    @Override
    public Boolean update(ErpWarehousing bo) {
        validEntityBeforeSave(bo);
        //获取子表
        List<ErpWarehousingInfo> infoList = bo.getContentInfo();
        infoList.forEach(x->{
            x.setOrderId(bo.getId());
            //如果列表中有新数据，执行新增
            if(x.getId() ==null){
                infoMapper.insert(x);
            }
            //旧数据则执行更新
            infoMapper.updateById(x);
        });
        //更新主表
        return baseMapper.updateById(bo) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpWarehousing entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采购入库
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
    /*审核*/
    @Override
    public void updateAudit(AuditDto dto) {
        LambdaUpdateWrapper<ErpWarehousing> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ErpWarehousing::getId,dto.getId());
        wrapper.set(ErpWarehousing::getAuditStatus,dto.getAuditStatus());//更新状态
        wrapper.set(ErpWarehousing::getAuditRemark,dto.getAuditRemark());//更新拒绝原因
        wrapper.set(ErpWarehousing::getAuditTime, new Date());//更新时间
        //查询主表
        ErpWarehousing warehousing = baseMapper.findById(dto.getId());
        //如果审核通过或单据作废执行
        if(dto.getAuditStatus() == 2 || dto.getAuditStatus() == 4){
            //TODO 如果单据已审核，则无法再次审核
            if (warehousing.getAuditStatus().equals(dto.getAuditStatus())){
                throw new RuntimeException("已审核");
            }
            //根据order_id查询Info表
            List<ErpWarehousingInfo> contentInfo = infoMapper.findByMainId(dto.getId());
            //TODO 这里应该做库存大于0的校验
            contentInfo.forEach(o->{
                //查询erp_products表
                ErpProducts goods = productsMapper.findById(o.getProductId());
                //根据info列表遍历出来后，更新erp_products表的stock字段
                ErpProducts product = new ErpProducts();
                //把主表的order名称和模块名设置到erp_goods_in_out_info表的相关字段
                ErpGoodsInOutInfo goodsInfo = new ErpGoodsInOutInfo();
                //TODO 查询多计量规格
                LambdaQueryWrapper<ErpUnitAttr> unitAttr = new LambdaQueryWrapper<>();
                unitAttr.eq(ErpUnitAttr::getProductId,o.getProductId());
                //根据商品所属多计量单位的主键ID查询其所属
                List<ErpUnitAttr> attrList = unitAttrMapper.selectList(unitAttr);
                //审核通过执行-加库存
                if(dto.getAuditStatus() == 2){
                    attrList.forEach(x->{
                        //如果attrs的id等于入库info表的specID,则进行计算
                        if(x.getId().equals(o.getProductSpecId())){
                            //TODO x.getAttrNum()*o.getAmount()+goods.getStock()得到新的值
                            product.setStock(x.getAttrNum().multiply(o.getAmount()).add(goods.getStock()));
                        }
                    });
                    //设置说明
                    goodsInfo.setRemark(warehousing.getRemark());
                }else{
                    //TODO 作废执行-减库存
                    product.setStock(goods.getStock().subtract(o.getAmount()));
                    goodsInfo.setRemark("单据作废");
                }
                //设置更新商品的ID
                product.setId(o.getProductId());
                //执行erp_products的更新方法
                productsMapper.updateById(product);
                //设置商品ID
                goodsInfo.setGoodsId(o.getProductId());
                //设置模块名称
                goodsInfo.setModuleName("采购入库");
                //设置订单名称
                goodsInfo.setOrderName(warehousing.getOrderNo());
                //设置分类
                goodsInfo.setCateId(o.getCateId());
                //TODO 设置规格,这里出库是以商品基本包装单位为准，所以不需要做多计量计算
                goodsInfo.setGoodsSpecId(goods.getUnitId());
                //变更后的新库存
                goodsInfo.setStock(product.getStock());
                //设置数量
                goodsInfo.setAmount(o.getAmount());
                //设置单价
                goodsInfo.setPrice(o.getPrice());
                //设置金额
                goodsInfo.setMoney(o.getMoney());
                //执行erp_goods_in_out_info添加方法
                goodsInOutInfoMapper.insert(goodsInfo);
            });
        }
        //执行主表更新方法
        baseMapper.update(wrapper);
    }
    /*生成默认标题*/
    @Override
    public String defaultTitle(String formatDate) {
        Integer totalNum = baseMapper.selectByBuyTimeCount(formatDate);
        //最低3位数，不足前面用0填充
        String format = String.format("%03d", totalNum);
        //拼接成新的标题
        return format;
    }
}
